package com.hxy.user.service.impl;

import com.hxy.basic.exception.BusinessExcpetion;
import com.hxy.basic.query.util.MD5Utils;
import com.hxy.basic.query.util.SmsUtil;
import com.hxy.basic.query.util.StrUtils;
import com.hxy.basic.service.impl.BaseServiceImpl;
import com.hxy.user.constant.Constant;
import com.hxy.user.domain.LoginInfo;
import com.hxy.user.domain.User;
import com.hxy.user.dto.UserDto;
import com.hxy.user.mapper.LoginInfoMapper;
import com.hxy.user.mapper.UserMapper;
import com.hxy.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 用户service接口实现类
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public void sendSms(String phone) {
        //1.验证 = 空值验证 + 是否注册过的验证
        if (!StringUtils.hasLength(phone)) {
            throw new BusinessExcpetion("请输入正确的手机号!!!");
        }
        User user = userMapper.findByPhone(phone);
        if(user != null){
            throw new BusinessExcpetion("该号码已经注册，请直接登录!!!");
        }

        //获取redis中保存的验证码
        Object obj = redisTemplate.opsForValue().get(Constant.REGISTER_CODE_PREFIX + phone);
        String code = null;
        if(obj != null){ //验证码没有过期
            //获取redis中以前保存的验证码
            code = obj.toString().split(":")[0];
            //获取以前保存的时间
            String timeString = obj.toString().split(":")[1];
            if(System.currentTimeMillis() - Long.parseLong(timeString) < 1*60*1000){ //没有过重发时间
                throw new BusinessExcpetion("不能重复发送验证码");
            }
        }else{ //过期了 或 第一次发送
            //重新生成验证码
            code = StrUtils.getRandomString(4);
        }

        redisTemplate.opsForValue().set(Constant.REGISTER_CODE_PREFIX + phone
                ,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
//        SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",小海我来了哟，Hxy");
        //SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
        System.out.println("你的验证码是：" + code + ",请在3分钟之内使用");
    }

    /**
     * 微信绑定发送手机验证码
     * @param phone
     */
    @Override
    public void sendBinderCode(String phone) {
        //1.验证 = 空值验证 + 是否注册过的验证
        if (!StringUtils.hasLength(phone)) {
            throw new BusinessExcpetion("请输入正确的手机号!!!");
        }
        User user = userMapper.findByPhone(phone);
        if(user != null){
            throw new BusinessExcpetion("该号码已经注册，请直接登录!!!");
        }

        //获取redis中保存的验证码
        Object obj = redisTemplate.opsForValue().get(Constant.BINDER_CODE_PREFIX + phone);
        String code = null;
        if(obj != null){ //验证码没有过期
            //获取redis中以前保存的验证码
            code = obj.toString().split(":")[0];
            //获取以前保存的时间
            String timeString = obj.toString().split(":")[1];
            if(System.currentTimeMillis() - Long.parseLong(timeString) < 1*60*1000){ //没有过重发时间
                throw new BusinessExcpetion("不能重复发送验证码");
            }
        }else{ //过期了 或 第一次发送
            //重新生成验证码
            code = StrUtils.getRandomString(4);
        }

        redisTemplate.opsForValue().set(Constant.BINDER_CODE_PREFIX + phone
                ,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
//        SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",小海我来了哟，Hxy");
        //SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
        System.out.println("你的微信登录验证码是：" + code + ",请在3分钟之内使用");
    }

    /**
     * 用户注册具体实现
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String password = userDto.getPassword();
        String rePassword = userDto.getRePassword();
        String verifycode = userDto.getVerifycode();

        // 空值校验
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifycode)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(rePassword)){
            throw new BusinessExcpetion("请输入正确的数据！");
        }
        // 判断两次密码是否相同
        if (!password.equals(rePassword)) {
            throw new BusinessExcpetion("两次输入的密码不一致！");
        }
        // 验证码是否过期
        Object obj = redisTemplate.opsForValue().get(Constant.REGISTER_CODE_PREFIX + phone);
        if (obj == null) {
            throw new BusinessExcpetion("验证码无效，请重新获取！");
        }
        // 验证码是否正确
        // 以冒号分隔 取第一个【0】
        String codeTmp = obj.toString().split(":")[0];
        if(!codeTmp.equalsIgnoreCase(verifycode)){
            throw new BusinessExcpetion("验证码错误!!!");
        }
        // 手机号码是否已经被注册了
        User userTmp = userMapper.findByPhone(phone);
        // 不为空时说明数据库中有这个手机号 已被注册
        if (userTmp != null) {
            throw new BusinessExcpetion("该号码已经注册，请直接登录!!!");
        }
        // 保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        LoginInfo logininfo = user2Logininfo(user);

        loginInfoMapper.save(logininfo);//获取自增id
        //2.2.再保存t_user
        user.setLogininfo_id(logininfo.getId());
        //user.setLogininfo(logininfo);
        userMapper.save(user);
    }
    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
    // 将 user
    private LoginInfo user2Logininfo(User user) {
        LoginInfo logininfo = new LoginInfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);
        //当前对象是用户
        logininfo.setType(1);
        return logininfo;
    }
}
